package cn.lingnan.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LargeModelUtils {


    private static final String USER_AGENT = "Java-HttpURLConnection/1.0";
    private static final String API_KEY = "sk-ff3f7df6cf644c5c9e2c27c682cea221"; // 固定的 API key
    private static final String URL_STR = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

    public static String getResponse(String userInput) throws Exception {
        HttpURLConnection connection = setupConnection();
        String jsonInputString = String.format(
                "{\"model\": \"qwen-turbo\", \"input\": {\"messages\": " +
                        "[{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}, " +
                        "{\"role\": \"user\", \"content\": \"%s\"}]}, " +
                        "\"parameters\": {\"result_format\": \"message\",\"incremental_output\":true}}",
                userInput
        );

        sendRequest(connection, jsonInputString);
        String responseContent = handleResponse(connection);

        connection.disconnect();
        return responseContent;
    }

    private static HttpURLConnection setupConnection() throws Exception {
        URL url = new URL(URL_STR);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
        connection.setRequestProperty("X-DashScope-SSE", "enable");
        connection.setDoOutput(true);
        return connection;
    }

    private static void sendRequest(HttpURLConnection connection, String jsonInputString) throws Exception {
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
            wr.flush();
        }
    }

    private static String handleResponse(HttpURLConnection connection) throws Exception {
        StringBuilder response = new StringBuilder();
        String regex = "\"content\":\"(.*?)\",\"role\"";
        Pattern pattern = Pattern.compile(regex);

        try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                if (inputLine.startsWith("data:")) {
                    String dataLine = inputLine.substring(5); // 去掉 "data:" 前缀
                    Matcher matcher = pattern.matcher(dataLine);
                    if (matcher.find()) {
                        response.append(matcher.group(1));
                    }
                }
            }
        }
        return response.toString();
    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
                System.out.println("请输入：");
                String userInput = scanner.nextLine();
                if (userInput.trim().isEmpty()) {
                    break; // 如果输入为空，退出循环
                }
                String response = LargeModelUtils.getResponse(userInput);
                System.out.println("模型生成回复：" + response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}